package com.runmonk.core.study.classloader;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * 自定义类加载器
 *
 * @author ：runmonk
 * @date ：Created in 2019/11/27 17:20
 */
public class MyTest15 extends ClassLoader {


    private String classLoaderName;

    private final String fileExtension = ".class";


    //定义构造器
    public MyTest15(String classLoaderName) {
        super();//隐式指定 父类加载器为系统类加载器
        this.classLoaderName = classLoaderName;
    }

    //定义构造器
    public MyTest15(ClassLoader parent, String classLoaderName) {
        super();//显示指定 父类加载器为系统类加载器
        this.classLoaderName = classLoaderName;
    }

    @Override
    public String toString() {
        return "[" + this.classLoaderName + "]";
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] data = this.loaderClassData(name);

        return this.defineClass(name, data, 0, data.length);
    }

    private byte[] loaderClassData(String name) {
        InputStream is = null;
        byte[] data = null;
        ByteArrayOutputStream baos = null;
        try {
            //文件路径名转换
            this.classLoaderName = this.classLoaderName.replace(".", "/");
            is = new FileInputStream(new File(name + this.fileExtension));
            int ch = 0;
            while (-1 != (ch = is.read())) {
                baos.write(ch);
            }
            data = baos.toByteArray();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return data;
    }

    public static void main(String[] args) throws Exception {
        MyTest15 mytest15 = new MyTest15("loader1");
        test(mytest15);
    }

    private static void test(ClassLoader classLoader) throws Exception {
        Class<?> clazz = classLoader.loadClass("com.runmonk.core.study.classloader.MyTest1");
        Object object = clazz.newInstance();//获取类的实例
        System.out.println(object);

    }




}


